from docx import Document

INPUT_DOCX = '代码导出结果.docx'
OUTPUT_DOCX = '代码导出结果_无空行.docx'

doc = Document(INPUT_DOCX)
new_doc = Document()

for para in doc.paragraphs:
    # 判断段落内容是否为空或全是空白字符
    if para.text.strip():
        new_para = new_doc.add_paragraph()
        for run in para.runs:
            new_run = new_para.add_run(run.text)
            new_run.bold = run.bold
            new_run.italic = run.italic
            new_run.underline = run.underline
            new_run.font.size = run.font.size
            new_run.font.name = run.font.name

# 保留分页符
for section in doc.sections:
    new_doc.add_section(section.start_type)

new_doc.save(OUTPUT_DOCX)
print(f'已生成无空行文档: {OUTPUT_DOCX}') 